<template>
	<view class="wrap">
		<js-error mode="bottom" ref="jsError" @update:errorcClose="onErrorClose"></js-error>
		<view class="cu-bar search" style="padding: 10px" ref="cu-bar">
			<u-search v-model="barCode" ref="uSearch" :focus="focus" placeholder="请先聚焦后扫描存货码" :show-action="false"
				@search="confirmSearch" height="74"></u-search>
			<view style="margin-left: 10px; display: flex; flex-direction: column">
				<u-icon @click="search" name="scan" size="60"></u-icon>
			</view>
		</view>
		<scroll-view
			class="scroll-list"
			:style="{ height: scrollViewHeight + 'px' }"
			scroll-y="true"
			@scrolltolower="loadMore"
			:refresher-enabled="true"
			:scrolltolower-enabled="true"
			:refresher-triggered="triggered"
			@refresherrefresh="refresherrefresh"
		>
			<view>
				<u-cell-group class="list" :border="false">
					<u-swipe-action  v-for="(item, index) in list" :key="item.id" :index="index">
						<u-cell-item :arrow="true" @click="handleCellItemClick(item)">
							<text slot="title">
								<view class="text-bold" :style="{ 'max-width': '100%', 'word-wrap': 'break-word', 'white-space': 'normal' }">{{ item.cinvname }}</view>
								<view class="text-sm">{{ item.cinvcode }}</view>
							</text>
						</u-cell-item>
					</u-swipe-action>
				</u-cell-group>
				<view v-if="list.length" class="loadmore" style="justify-self: flex-end">
					<u-loadmore :status="loadStatus"></u-loadmore>
				</view>
				<u-empty v-if="!list.length" style="height: 100%;"></u-empty>
			</view>
      </scroll-view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				focus:true,
				barCode:'',
				model: {
					iqty:'',
					operator:''
				},
				rules: {
					operator: [
						{
							required: true,
							message: '请扫码操作工',
							trigger: ['change','blur'],
						}
					]
				},
				customStyle:{
					color:'red'
				},
				scrollViewHeight: 0,
				currentRW:false,
				emptyViewHeight:0,
				list:[],
				modid:'',
				lineCode:'',
				flag:false,
				loadStatus: "loadmore",
				triggered: false,
				query: {
					pageNo: 1,
					pageSize: 20,
				},
			}
		},
		// mounted() {
		// 	this.calculateScrollViewHeight()
		// 	this.emptyHeight()
		// },
		onLoad() {
			this.$nextTick(() => {
				this.calculateScrollViewHeight()
				this.emptyHeight()
			})
			this.loadData();
		},
		computed: {
		  computedScrollViewHeight() {
		    return this.scrollViewHeight === 'auto' ? 'auto' : `${this.scrollViewHeight}px`;
		  },
		},
		methods:{
			async calculateScrollViewHeight() {
			  try {
			// 等待头部高度计算完成
			      console.log(this.$refs,'this.$refs')
			      // 计算btn-group 高度
			      // 获取屏幕高度
			      const systemInfo = uni.getSystemInfoSync();
			      const screenHeight = systemInfo.windowHeight;
				  const cuBarOffsetHeight = this.$refs['cu-bar'] ? this.$refs['cu-bar'].$el ? this.$refs['cu-bar'].$el.offsetHeight : 54 : 0 ;
			      // 计算scroll-view高度
			      this.scrollViewHeight = screenHeight - ( cuBarOffsetHeight + 10 );
			  } catch (error) {
			    console.error('Error while calculating ScrollView height:', error);
			  }
			},
			async emptyHeight() {
			  try {
			      // 获取屏幕高度
			      const systemInfo = uni.getSystemInfoSync();
			      const screenHeight = systemInfo.windowHeight;
				  const cuBarOffsetHeight = this.$refs['cu-bar'] ? this.$refs['cu-bar'].$el ? this.$refs['cu-bar'].$el.offsetHeight : 54 : 0;
			      // 计算scroll-view高度
			      this.emptyViewHeight = screenHeight - cuBarOffsetHeight;
			  } catch (error) {
			    console.error('Error while calculating ScrollView height:', error);
			  }
			},
			confirmSearch(){		
				this.focus = false
				this.commonSearch(this.barCode)
			},
			async commonSearch(barCode){				
				let JT = this.vuex_config.JT;
				let GP = this.vuex_config.GP;
				let xmPrefix = this.vuex_config.xmPrefix;
				console.log(this.barCode.indexOf(JT),'JT',this.barCode,JT,this.barCode.indexOf(GP))
				if (barCode.indexOf(xmPrefix) == -1) {
					this.$refs.jsError.showError('',"请扫描正确的箱码",'error');
					return;
				}else if(barCode.indexOf(xmPrefix) == 0){
					let bar = encodeURIComponent(barCode);
					const res = await this.$u.api.kst.readBar({
						cbarcode: bar,
					})
					if (res.result == "true") {
						await this.$nextTick();
						this.barCode = '';
						console.log(res,'res')
						uni.navigateTo({
							url: "/pages/mes/files/list?bizKey=" + res.data.contentVo.invCode
						});

					}else{
						setTimeout(() => {
							this.focus = true;
						}, 500);
						this.$refs.jsError.showError('',res.message,'error');
						
					}
				} 
				
			},
			handleCellItemClick(item) {
				uni.navigateTo({
					url: "/pages/mes/files/list?bizKey=" + item.cinvcode
				});
			},

			confirm(){
				// 获取list的id,字符串逗号分隔
				this.$u.api.kst.taskDown({
					lineCode:this.lineCode
				}).then((res)=>{
					if(res.result=="true"){
						this.flag = true
						this.$u.toast(res.message);
					}else{
						// this.$u.toast(res.message);
						this.$refs.jsError.showError('',res.message,'error');
					}
				})

			},
			search(){
				var _that = this;
				_that.focus = false
				uni.scanCode({
					scanType: ["barCode", "qrCode"],
					// onlyFromCamera: true,
					success: async (res) => {
						_that.barCode = res.result;
						await _that.commonSearch(res.result)
					},
				});
			},
			onErrorClose(result) {
				this.focus = result;
				setTimeout(() => {
					this.barCode = ''
					this.focus = true;
				}, 100);
			 
			},
	  loadMore() {
        this.loadStatus = "loading";
        setTimeout(() => {
          this.query.pageNo += 1;
          this.loadData("add");
        }, 100);
      },
      async refresherrefresh() {
        this.triggered = true;
        this.query.pageNo = 1;
        await this.loadData();
        setTimeout(() => {
          this.triggered = false;
        }, 500);
        // this.triggered = false;
      },
      loadData(type) {
        this.$u.api.kst.invListData(this.query).then((res) => {
          console.log(res);
          this.show = false;
          if (res.list.length < 20 || res.list.length == 0) {
            this.loadStatus = "nomore";
            this.list = res.list;
          }else{
              var data = res.list;
              // 添加isReadBlockVisible 属性
              if (type == "add") {
                for (var i = 0; i < data.length; i++) {
                  this.list.push(data[i]);
                }
              } else {
                this.list = data;
              }
          }
        });
      },
		}
	}	
</script>

<style scoped>
	.title{
		width: 180rpx;
	}
	.bg-confirm {
	  background: #3e97b0;
	  color: #ffffff;
	}
	.title{
		width: 180rpx;
	}
</style>